
let pageSelect;
let isSearchMode = false;
let currentSearchTerm = '';
let selectedType = '';
/**
 * 加载文章
 * @param {*} currentPage 当前页码
 * @param {*} pageSize 每页数量
 * @returns 
 */
async function loadArticles(currentPage = 1, pageSize = 10) {
    try {
        let url = `../php/home.php?currentPage=${currentPage}&pageSize=${pageSize}`;
        if (isSearchMode && currentSearchTerm) {
            url += `&searchStr=${currentSearchTerm}`;
        }
        if (selectedType) {
            url += `&typeId=${selectedType}`;
        }
        
        const response = await fetch(url, {
            method: 'GET'
        });

        if (!response.ok) {
            throw new Error('加载失败');
        }
        
        const data = await response.json();
        if (data.success) {
            showSearchResults(data.data.data);
            
            // 更新分页信息
            if (!pageSelect) {
                pageSelect = new PageSelect('pagination', {
                    currentPage: data.data.current_page,
                    pageSize: data.data.page_size,
                    totalPages: data.data.total_pages,
                    onChange: (page, size) => loadArticles(page, size)
                });
            } else {
                pageSelect.update({
                    currentPage: data.data.current_page,
                    totalPages: data.data.total_pages
                });
            }
        } else {
            showError(data.msg || '加载失败');
        }
    } catch (error) {
        console.error('加载错误:', error);
        showError('加载过程中发生错误，请稍后重试');
    }
}

// /**
//  * 处理登录和退出
//  */
// function handleLoginLogout() {
//     const { isLoggedIn } = checkLogin();
//     if (isLoggedIn) {
//         localStorage.removeItem('xlsystem_user');
//         updateLogBtnStatus();
//     } else {
//         window.location.href = '../html/login.html';
//     }
// }

// 搜索功能
async function handleSearch() {
    const searchInput = document.getElementById('searchInput');
    const searchTerm = searchInput.value.trim();
    
    if (!searchTerm) {
        isSearchMode = false;
        currentSearchTerm = '';
        loadArticles(1);
        return;
    }

    isSearchMode = true;
    currentSearchTerm = searchTerm;
    loadArticles(1);
}

/**
 * 搜索结果模板
 * @param {*} results 
 * @returns 
 */
function showSearchResults(results) {
    const searchResults = document.getElementById('searchResults');
    
    if (!results || results.length === 0) {
        searchResults.innerHTML = '<div class="no-results">没有找到相关文章</div>';
        return;
    }

    const resultsHtml = results.map(result => `
        <div class="search-result-item" onclick="toArticleDetail(${result.id})">
            <div class="result-left">
                <img src="${result.img || '../assets/default-cover.png'}" alt="${result.title}" class="result-cover">
            </div>
            <div class="result-right">
                <div class="search-result-title">${result.title}</div>
                <div class="search-result-brief">${result.brief || '暂无简介'}</div>
                <div class="search-result-content">${result.content || '暂无内容'}</div>
                <div class="result-meta">
                    <span class="result-source">${result.source || '未知来源'}</span>
                    <span class="result-date">${new Date(result.update_time).toLocaleDateString()}</span>
                    <span class="result-author">作者：${result.create_user || '未知'}</span>
                </div>
            </div>
        </div>
    `).join('');

    searchResults.innerHTML = resultsHtml;
}

/**
 * 显示错误信息
 * @param {*} message 错误信息
 */
function showError(message) {
    const searchResults = document.getElementById('searchResults');
    searchResults.innerHTML = `<div class="no-results">${message}</div>`;
}




/**
 * 跳转至文章详情
 */
function toArticleDetail(id){
    window.location.href = `../html/detail.html?mentalId=${id}`;
}

/**
 * 初始化页面
 */
document.addEventListener('DOMContentLoaded', () => {

    getTypes();

    loadArticles();
});